<template>
  <container-wrapper
    :designer="designer"
    :widget="widget"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :entityWarn="!entityInfo"
  >
    <div
      :key="widget.id + keyValue"
      class="data-column"
      :class="[
        selected ? 'selected' : '',
        customClass,
        entityInfo ? '' : 'noEntity',
      ]"
      @click.stop="selectWidget(widget)"
    >
      <table class="table-layout" :key="JSON.stringify(widget)">
        <thead>
          <tr v-if="widget.rows[0]">
            <th
              v-for="item in widget.rows[0].cols"
              :key="item.value"
              class="header"
              :class="[item.title ? '' : 'noAttr']"
            >
              <div class="headerContent">{{ item.title || "Column" }}</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIdx) in widget.rows" :key="row.id">
            <template v-for="(colWidget, colIdx) in row.cols">
              <table-column-widget
                v-if="!colWidget.merged"
                :widget="colWidget"
                :designer="designer"
                :key="colWidget.id"
                :parent-list="widget.cols"
                :row-index="rowIdx"
                :row-length="widget.rows.length"
                :col-index="colIdx"
                :col-length="row.cols.length"
                :col-array="row.cols"
                :row-array="widget.rows"
                :parent-widget="widget"
              ></table-column-widget>
            </template>
          </tr>
        </tbody>
      </table>
    </div>
  </container-wrapper>
</template>

<script>
import i18n from "@/utils/i18n";
import containerMixin from "@/components/form-designer/form-widget/container-widget/containerMixin";
import ContainerWrapper from "@/components/form-designer/form-widget/container-widget/container-wrapper";
import TableCellWidget from "@/components/form-designer/form-widget/data-widget/table-column-widget";
import refMixinDesign from "@/components/form-designer/refMixinDesign";
import * as api from "@/api/modulManage/entity";
import { deepClone, generateId } from "@/utils/util";

export default {
  name: "data-column-widget",
  componentName: "DataColumWidget",
  mixins: [i18n, containerMixin, refMixinDesign],
  inject: ["refList"],
  components: {
    ContainerWrapper,
    TableCellWidget,
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
  },
  computed: {
    selected() {
      return this.widget.id === this.designer.selectedId;
    },

    customClass() {
      return this.widget.options.customClass || "";
    },
    entityInfo() {
      return this.widget.options.entity;
    },
  },
  watch: {
    // 监听实体变化
    "widget.options.entity": {
      handler(val) {
        if (val) {
          this.coverConfirm(val);
        }
      },
      // deep: true,
      // immediate: true,
    },
    // 监听操作栏变化
    "widget.options.dataColumnConfig.operateColumn": {
      handler(val) {
        if (val) {
          // 如果已经有操作栏
          // 添加操作栏
          if (
            this.parentList[0] &&
            this.parentList[0].options.label === "操作栏"
          ) {
            return;
          }
          const operateWidget = this.designer.addTableButtonWidget();
          this.parentList.unshift(operateWidget);
        } else {
          // 有操作栏时才能删除
          if (
            this.parentList[0] &&
            this.parentList[0].options.label === "操作栏"
          ) {
            // 删除操作栏
            this.parentList.shift();
          }
        }
      },
      deep: true,
      immediate: true,
    },
    // 监听分页变化
    "widget.options.dataColumnConfig.pagination": {
      handler(val) {
        if (val) {
          // 有分页的return
          if (this.parentList.some((v) => v.type === "el-pagination")) {
            return;
          }
          // 添加分页模块
          const pageField = this.designer.copyNewFieldWidget(
            this.designer.getFieldWidgetByType("el-pagination")
          );
          let indexValue = 0;
          this.parentList.forEach((v, index) => {
            if (v.type === "data-column") {
              indexValue = index;
            }
          });
          this.parentList.splice(indexValue + 1, 0, pageField);
        } else {
          // 删除分页模块
          let indexValue = 0;
          this.parentList.forEach((v, index) => {
            if (v.type === "el-pagination") {
              indexValue = index;
            }
          });
          this.parentList.splice(indexValue, 1);
        }
      },
      deep: true,
      immediate: true,
    },
    // 监听列变化
    "widget.rows": {
      handler(val) {
        if (!val || !val[0]) {
          return;
        }
        if (this.designer.attrList.length === 0) {
          try {
            if(!this.widget.options.entity){
              return
            }
            api.getTypeAllAttributeByName({ typeName: this.widget.options.entity }).then((res) => {
              this.designer.loadingData = false;
              if (!res.data || !res.data.data) {
                return;
              }
              this.designer.attrList = [...res.data.data];
              // this.updateDialog();
            });
          } catch (err) {
            this.designer.loadingData = false;
          }
        } else {
          // this.updateDialog();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.initRefList();
  },
  mounted() {},
  methods: {
    updateDialog() {
      if(!this.widget[0]){
        return
      }
      // 根据列变化更新弹框
      const attrList = this.widget[0].cols.map((v) => v.value).filter((v) => !!v);
      console.log("attrListattrList", attrList);
      const attrListNew = this.designer.attrList.filter(
        (v) => attrList.indexOf(v.columnName) > -1
      );
      this.designer.colAttrList = [...attrListNew];
      // this.addDialogAndForm(attrListNew);
    },
    addDialogAndForm(attrListNew) {
      const dialogId = "操作弹框" + this.widget.id;
      let dialogField = this.designer.copyNewContainerWidget(
        this.designer.getContainerByType("el-dialog")
      );
      let hasDialog = false;
      //如果弹框存在
      console.log("this.parentList", this.parentList);
      if (this.parentList.some((v) => v.label === dialogId)) {
        hasDialog = true;
        [dialogField] = this.parentList.filter((v) => v.label === dialogId);
        console.log("如果弹框存在", dialogField);
      }

      const dataView = this.designer.copyNewContainerWidget(
        this.designer.getContainerByType("data-view")
      );
      this.designer.addDataScript(dataView);
      dataView.options.entity = this.widget.options.entity;
      const attrList =
        attrListNew || this.designer.colAttrList || this.designer.attrList;
      dataView.options.attrList = [...attrList];
      dialogField.widgetList = [dataView];
      dialogField.label = "操作弹框" + this.widget.id;
      if (!hasDialog) {
        this.parentList.push(dialogField);
      }
    },
    addSearchForm(){
      let searchContainer = this.designer.copyNewContainerWidget(
        this.designer.getContainerByType("box-container")
      );
    },
    coverConfirm(val) {
      const that = this;
      this.$confirm("是否要自动填充数据视图的内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          that.updateTableByEntity(val);
        })
        .catch(() => {});
    },
    updateTableByEntity(val) {
      if (!val) {
        return;
      }
      this.designer.loadingData = true;
      try {
        
        api.getTypeAllAttributeByName({ typeName: val }).then((res) => {
          this.designer.loadingData = false;
          if (!res.data || !res.data.data) {
            return;
          }
          const entityData = res.data.data;
          this.designer.attrList = [...res.data.data];
          this.designer.colAttrList = [...res.data.data];
          // 获取表头
          const headData = entityData.map((v) => ({
            label: v.nameCn,
            value: v.columnName,
            visible: true,
            columnType: v.columnType,
          }));
          this.headData = headData;
          this.initHeadData = [...headData];
          // 处理列
          let newRow = { cols: [], title: "" };
          newRow.id = "table-row-" + generateId();
          newRow.merged = false;
          headData.map((v) => {
            let newCell = deepClone(
              this.designer.getContainerByType("table-column")
            );
            newCell.id = "table-column-" + generateId();
            newCell.options.name = newCell.id;
            newCell.merged = false;
            newCell.value = v.value;
            newCell.title = `${v.label}`;
            newCell.options.colspan = 1;
            newCell.options.rowspan = 1;
            newCell.options.fieldAttribute = v.value;
            newRow.cols.push(newCell);
            return null;
          });
          this.widget.rows = [newRow];
          this.widget.options.dataColumnConfig.operateColumn = true;
          //创建弹框及表单
          // this.addDialogAndForm();
        });
      } catch (err) {
        this.designer.loadingData = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
div.data-column {
  padding: 5px;
  border: 1px dashed #336699;
  box-sizing: border-box;
  overflow-x: scroll;
  &.noEntity {
    border: 1px dashed red;
  }
  table.table-layout {
    width: 100%;
    text-align: center;
    //border: 1px solid #c8ebfb;
    border-collapse: collapse;
    table-layout: fixed;
    .header {
      width: 120px;
      min-width: 100px;
      padding: 5px;
      overflow: hidden;
      border: 1px dashed #336699;
      &.noAttr {
        border: 1px dashed red;
      }
      .headerContent {
        font-weight: 600;
        white-space: nowrap;
        overflow: hidden;
        // width: 200px;
        font-size: 14px;
        height: 48px;
        line-height: 48px;
      }
    }
    ::v-deep td {
      height: 48px;
      border: 1px dashed #336699;
      padding: 3px;
      display: table-cell;
    }

    .form-widget-list {
      // border: 1px dashed #336699;
      min-height: 36px;
    }
  }
}

.data-column.selected {
  outline: 2px solid $--color-primary !important;
}
</style>
